package NG::Sys::Cfg;
use strict;
use warnings;
use utf8;

use Cwd qw(realpath);

use base 'Exporter';
my %configs;
our $path = "../cfg";
our @EXPORT = qw(config appconfig);

sub config {
	my ($name) = @_;
	$name ||= "main";
	my $config;
	if($config = $configs{$name}){
		return $config;
	}
	my $fn = $path."/".$name.".cfg";
	my $str = "";
	local *F;
	if(open F,$fn){
		binmode F,":utf8";
		local $/;
		$str = <F>;
		close F;
	}
	eval "\$config = {".$str."}";
	if($@){
		die "$fn: $@";
	}
	return $configs{$name} = $config;
}
sub appconfig{
	local $path = "../cfgapp";
	return config(@_);
}
sub reference {
	my $name = shift;
	my $map = shift;
	tie my @ary,'LazyReference',$name,$map;
	return \@ary;
}

package LazyReference;
sub TIEARRAY{
	my $class = shift;
	my $name = shift;
	my $map = shift;

	unless($name){
		die "need name";
	}
	unless($map){
		die "need map";
	}
	unless($map->{value}){
		die "need map->{value}";
	}
	unless($map->{title}){
		die "need map->{title}";
	}
	
	return bless {
			name => $name,
			value => $map->{value},
			title => $map->{title},
		}, $class;
}
sub FETCH{
	my $self = shift;
	my $index = shift;
	$self->check;
	return $self->{list}[$index];
}
sub FETCHSIZE{
	my $self = shift;
	$self->check;
	return scalar @{$self->{list}};
}
sub check {
	my $self = shift;
	unless($self->{list}){
		require NG::Sys::App;
		my $ref = NG::Sys::App::app()->reference($self->{name});
		my @list;
		for my $row(@{$ref->get_list}){
			push @list,{
				value => $row->{$self->{value}},
				title => $row->{$self->{title}},
			};
		}
		$self->{list} = \@list;
	}
	return $self->{list};
}

1;
